package documentation_logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateDocumentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewCreateDocumentLogic 创建知识库
func NewCreateDocumentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateDocumentLogic {
	return &CreateDocumentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateDocumentLogic) CreateDocument(req *types.CreateDocumentReq) (resp *types.CreateDocumentResp, err error) {
	// 输入验证
	if req.Title == "" || req.Author == "" || req.Content == "" || req.Component == "" {
		err = errors.New("title, author, content, and component cannot be empty")
		l.Logger.Error(err)
		return &types.CreateDocumentResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	// 将 tags 转换为 JSON
	tags, err := json.Marshal(req.Tags)
	if err != nil {
		l.Logger.Error("Failed to marshal tags", logx.Field("error", err))
		return nil, err
	}

	// 执行插入操作
	query := fmt.Sprintf(`INSERT INTO %s (title, author, content, component, tags) VALUES (?, ?, ?, ?, ?)`, l.svcCtx.Config.Mysql.Tables.DocumentationKnowledge)
	result, err := l.svcCtx.Conn.ExecCtx(l.ctx, query, req.Title, req.Author, req.Content, req.Component, tags)
	if err != nil {
		l.Logger.Error("Failed to execute insert query", logx.Field("error", err))
		return nil, err
	}

	// 获取插入的 ID
	id, err := result.LastInsertId()
	if err != nil {
		l.Logger.Error("Failed to get last insert ID", logx.Field("error", err))
		return nil, err
	}

	return &types.CreateDocumentResp{
		Code:    200,
		Message: "Document created successfully",
		Data:    &types.Document{Id: id, Title: req.Title, Author: req.Author, Content: req.Content, Component: req.Component, Tags: req.Tags},
	}, nil
}
